package tr.richfacesext.components.captcha.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.StateHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.commons.lang.StringUtils;

import tr.richfacesext.components.captcha.CaptchaConstants;

/**
 * 
 * @author mert
 *
 */
public class CaptchaValidator implements Validator, StateHolder {

	private String captchaId;
	
	private String valueRequiredMsg;
	
	private String textNotMatchMsg; 
	
	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

		if (StringUtils.isEmpty(getValueRequiredMsg()))
			//TODO
//			setValueRequiredMsg(JsfUtil.getString(CaptchaConstants.KEYVAL_CAPTCHA_ERR_MESSAGE_VALUEREQUIRED));
			setValueRequiredMsg(CaptchaConstants.KEYVAL_CAPTCHA_ERR_MESSAGE_VALUEREQUIRED);
		if (StringUtils.isEmpty(getTextNotMatchMsg()))
			//TODO
//			setTextNotMatchMsg(JsfUtil.getString(CaptchaConstants.KEYVAL_CAPTCHA_ERR_MESSAGE_TEXTNOTMATCH));
			setTextNotMatchMsg(CaptchaConstants.KEYVAL_CAPTCHA_ERR_MESSAGE_TEXTNOTMATCH);
			
		String val = StringUtils.strip((String)value);
		String captchaValue = (String) context.getApplication().getVariableResolver().resolveVariable(context, getCaptchaId()); 
		
		if (StringUtils.isEmpty(val)) { 
			throw new ValidatorException(new FacesMessage(valueRequiredMsg, valueRequiredMsg));
		}
		

		if (!StringUtils.equals(val, captchaValue)) {
			throw new ValidatorException(new FacesMessage(textNotMatchMsg, textNotMatchMsg));
		}
	}

	public boolean isTransient() {
		return false;
	}
	
	public void setTransient(boolean isTransient) {
		//No-op
	}

	public void restoreState(FacesContext context, Object state) {
		Object values[] = (Object[]) state;
		captchaId = (String) values[0];
		textNotMatchMsg = (String) values[1]; 
		valueRequiredMsg = (String) values[2];
	}

	public Object saveState(FacesContext context) {
		Object values[] = new Object[3];
		values[0] = captchaId;
		values[1] = textNotMatchMsg;
		values[2] = valueRequiredMsg;
		return ((Object) values);
	}
	
	public String getCaptchaId() {
		return captchaId;
	}

	public void setCaptchaId(String captchaId) {
		this.captchaId = captchaId;
	}
	
	public String getTextNotMatchMsg() {
		return textNotMatchMsg;
	}

	public void setTextNotMatchMsg(String textNotMatchMsg) {
		this.textNotMatchMsg = textNotMatchMsg;
	}

	public String getValueRequiredMsg() {
		return valueRequiredMsg;
	}

	public void setValueRequiredMsg(String valueRequiredMsg) {
		this.valueRequiredMsg = valueRequiredMsg;
	}
}